package cn.wildfire.chat.app.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kyleduo.switchbutton.SwitchButton;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.R;
import com.sourcemuch.im.caiba.R2;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.Config;
import cn.wildfire.chat.app.extendsion.BaseActivity;
import cn.wildfire.chat.app.extendsion.classes.CheckVersionReq;
import cn.wildfire.chat.app.extendsion.classes.LoginRequest;
import cn.wildfire.chat.app.extendsion.classes.Region;
import cn.wildfire.chat.app.extendsion.utils.OSHelper;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.login.SMSLoginActivity;

/**
 * Create by HEKE, 2019/8/12 19:41
 * TODO 新版登入界面
 */
@SuppressLint("SetTextI18n")
public class LoginActivity extends BaseActivity {

    @BindView(R2.id.phoneNymber)
    EditText phoneNymber;
    @BindView(R2.id.password)
    EditText password;
    @BindView(R2.id.loginBut)
    Button loginBut;
    @BindView(R2.id.smsLoginTxt)
    TextView smsLoginTxt;
    @BindView(R2.id.countrySelector)
    TextView countrySelector;
    @BindView(R2.id.selectedCountryTxt)
    TextView selectedCountryTxt;
    @BindView(R2.id.forgetPaaword)
    TextView forgetPaaword;
    @BindView(R2.id.remenberSwitchButton)
    SwitchButton remenberSwitchButton;
    @BindView(R2.id.registerTxt)
    TextView registerTxt;
    @BindView(R2.id.iv_password_hide_or_show)
    ImageView ivPasswordHideOrShow;
    @BindView(R2.id.wxLogin)
    ImageView wxLogin;
    @BindView(R2.id.quickLoginLayout)
    RelativeLayout quickLoginLayout;
    @BindView(R2.id.quickWxIconLayout)
    LinearLayout quickWxIconLayout;

    /**
     * 记录账号密码开关
     */
    private boolean remenberTag;

    /**
     * 传入数据
     */
    private String usernameVal;
    private String passwordVal;
    private Region mRegion;

    /**
     * 当前选中的国家区号
     */
    private Region currentRegion;

    /**
     * 版本检测
     */
    protected CheckVersionReq checkVersionReq;

    /**
     * 微信
     */
    protected IWXAPI iwxapi;
    protected BroadcastReceiver wxBroadcastReceiver;

    @Override
    public void initViews() {
        bindBack();
        setLevel(2);
        hideToolbar();
        try {
            iwxapi = WXAPIFactory.createWXAPI(this, Config.WXAppID, true);
            iwxapi.registerApp(Config.WXAppID);
            //建议动态监听微信启动广播进行注册到微信
            wxBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    // 将该app注册到微信
                    iwxapi.registerApp(Config.WXAppID);
                }
            };
            registerReceiver(wxBroadcastReceiver, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));

            // 判断是否记录账号密码
            String value = SPUtils.getSingle(this, "REMENBER", "remenber");
            remenberTag = value.equals("1");
            remenberSwitchButton.setCheckedNoEvent(remenberTag);
            remenberSwitchButton.setOnCheckedChangeListener(onCheckedChangeListener);
            // 获取传入信息
            Intent intent = getIntent();
            if (intent != null) {
                usernameVal = intent.getStringExtra("username");
                passwordVal = intent.getStringExtra("password");
                mRegion = intent.getParcelableExtra("region");
                currentRegion = mRegion;
            }
            if (mRegion == null) {
                currentRegion = new Region(438, "86", getString(R.string.default_country));
            }
            // 根据记录状态设置账号密码显示
            if (remenberTag) {
                String[] array = SPUtils.getMuches(this, "REMENBER_CONTENT", new String[]{"account", "password", "region"});
                if (!TextUtils.isTextEmpty(array[2])) {
                    usernameVal = array[0];
                    passwordVal = array[1];
                    currentRegion = new Region(array[2]);
                    password.setText(passwordVal);
                }
            } else {
                //记住上次登录的账号
                String[] array = SPUtils.getMuches(this, "REMENBER_CONTENT", new String[]{"account", "region"});
                if (!TextUtils.isTextEmpty(array[1])) {
                    usernameVal = array[0];
                    currentRegion = new Region(array[1]);
                }
            }
            selectedCountryTxt.setText(currentRegion.regionName);
            phoneNymber.setText((TextUtils.isTextEmpty(usernameVal) ? "" : usernameVal));
            phoneNymber.addTextChangedListener(textWatcher);
            password.addTextChangedListener(pstextWatcher);

            // 微信APP安装检测，未安装则隐藏快速登录接口
            boolean isUserInstalledWeiXinApp = OSHelper.checkApkExist(this, OSHelper.WX_APP_PACKAGENAME);
            quickLoginLayout.setVisibility(isUserInstalledWeiXinApp ? View.VISIBLE : View.GONE);
            quickWxIconLayout.setVisibility(isUserInstalledWeiXinApp ? View.VISIBLE : View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_login);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        checkVersionReq = new CheckVersionReq(this);
    }

    @Override
    protected void onPause() {
        if (checkVersionReq != null) {
            checkVersionReq.dismiss();
        }
        super.onPause();
    }

    /**
     * 账号输入内容检测
     */
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    /**
     * 密码输入内容检测
     */
    private TextWatcher pstextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            try {
                // 密码长度处理
                String pwtxt = editable.toString();
                if (!TextUtils.isTextEmpty(pwtxt)) {
                    int maxLength = 12;
                    int length = pwtxt.length();
                    if (length > maxLength) {
                        password.setText(pwtxt.substring(0, maxLength));
                        password.setSelection(maxLength);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @OnClick({R2.id.loginBut, R2.id.smsLoginTxt, R2.id.registerTxt, R2.id.forgetPaaword, R2.id.wxLogin})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.loginBut) {
            String account = phoneNymber.getText().toString();
            String password2 = password.getText().toString();
            new LoginRequest(this, account, password2, currentRegion, remenberTag);
        } else if (id == R.id.smsLoginTxt) {
            Intent toSmsLogin = new Intent(this, SMSLoginActivity.class);
            toSmsLogin.putExtra("Region", currentRegion);
            startActivity(toSmsLogin);
        } else if (id == R.id.registerTxt) {
            Intent toRegister = new Intent(this, RegisterActivity.class);
            toRegister.putExtra("Region", currentRegion);
            startActivity(toRegister);
        } else if (id == R.id.forgetPaaword) {
            Intent intentForgetPssword = new Intent(this, ForgetPasswordInputPhoneActivity.class);
            startActivity(intentForgetPssword);
        } else if (id == R.id.wxLogin) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "sourcemuch_wechat_sdk";
            iwxapi.sendReq(req);
        }
    }

    /**
     * 开关按钮
     */
    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            remenberTag = b;
            SPUtils.setSingle(LoginActivity.this, "REMENBER", "remenber", b ? "1" : "0");
        }
    };

    @OnClick(R2.id.countrySelector)
    public void onViewClicked() {
        Intent intent = new Intent(LoginActivity.this, CountrySetActivity.class);
        intent.putExtra("RegionList", ((CaiBaChatApp) getApplicationContext()).regionFetcher.getmRegionRet());
        startActivityForResult(intent, 101);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调选择国家编码
        try {
            if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
                currentRegion = data.getParcelableExtra("mRegion");
                if (currentRegion != null) {
                    selectedCountryTxt.setText(currentRegion.regionName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean passwordShow = false;

    @OnClick({R2.id.tv_privacy_policy, R2.id.iv_password_hide_or_show})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_privacy_policy) {
            Intent intent = new Intent(this, UserAgrementActiviy.class);
            startActivity(intent);
        } else if (id == R.id.iv_password_hide_or_show) {
            if (passwordShow) {
                passwordShow = false;
                ivPasswordHideOrShow.setImageResource(R.mipmap.password_hide);
                password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                password.setSelection(password.getText().toString().length());
            } else {
                passwordShow = true;
                ivPasswordHideOrShow.setImageResource(R.mipmap.password_show);
                password.setInputType(InputType.TYPE_CLASS_TEXT);
                password.setSelection(password.getText().toString().length());
            }
        }
    }


    PopupWindow popupWindow;

    public void ShowPopWindow() {

        View view = LayoutInflater.from(this).inflate(R.layout.pop_clear_cache, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);

        Button cancel = view.findViewById(R.id.btn_cancel);
        Button confirm = view.findViewById(R.id.btn_confirm);
        TextView tvReminder = view.findViewById(R.id.tv_reminder);
        tvReminder.setText(getString(R.string.password_protected_not_set));
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                popupWindow.dismiss();
                finish();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, SetSecurityQuestionActivity.class);
                intent.putExtra("AddPasswordProtected", "AddPasswordProtected");
                startActivity(intent);
                popupWindow.dismiss();
            }
        });


        setAlph(0.9f);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlph(1f);
            }
        });

    }

    private void setAlph(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        //0.0-1.0
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onDestroy() {
        try {
//            if (wxBroadcastReceiver != null && wxBroadcastReceiver.isOrderedBroadcast()) {
                unregisterReceiver(wxBroadcastReceiver);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        try {
            moveTaskToBack(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
